package com.ylr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylr.domain.SysUserRole;
import com.ylr.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylr.mapper.SysUserMapper;
import com.ylr.domain.SysUser;
import com.ylr.service.SysUserService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 分页查询员工
     *
     * @param page     分页参数
     * @param mobile   员工的手机号
     * @param fullname 员工的全名称
     * @return
     */
    @Override
    public Page<SysUser> findByPage(Page<SysUser> page, String mobile, String fullname) {
        Page<SysUser> pageData = page(page,
                new LambdaQueryWrapper<SysUser>()  //LambdaQueryWrapper是mybatis plus中的一个条件构造器对象，只是是需要使用Lambda 语法使用 Wrapper
                        .like(!StringUtils.isEmpty(mobile), SysUser::getMobile, mobile)  //public Children like(boolean condition, R column, Object val)第一个参数 boolean condition 表示该条件是否加入最后生成的sql中
                        .like(!StringUtils.isEmpty(fullname), SysUser::getFullname, fullname)

        );
        List<SysUser> records = pageData.getRecords();  //获得记录列表
        //判断sys用户记录是否为空
        if (!CollectionUtils.isEmpty(records)) {
            //sys用户不为空，取出记录，然后根据sys用户查询角色信息。
            for (SysUser sysUser : records) {
                List<SysUserRole> userRoles = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, sysUser.getId()));
                //如果角色信息不为空，根据角色用户表，返回角色id并保存
                if (!CollectionUtils.isEmpty(userRoles)) {
                    sysUser.setRole_strings(
                            userRoles.stream().
                                    map(sysUserRole -> sysUserRole.getRoleId().toString())
                                    .collect(Collectors.joining(",")));
                }


            }

        }


        return pageData;
    }


    /**
     * 新增员工
     *
     * @param sysUser
     * @return
     */
    @Override
    @Transactional
    public boolean addUser(SysUser sysUser) {
        // 1 用户的密码
        String password = sysUser.getPassword();
        // 用户的角色Ids
        String role_strings = sysUser.getRole_strings();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encode = bCryptPasswordEncoder.encode(password); // 加密密码
        sysUser.setPassword(encode); // 设置密码
        boolean save = super.save(sysUser);
        if(save){
            // 给用户新增角色数据
            if(!StringUtils.isEmpty(role_strings)){
                String[] roleIds = role_strings.split(",");
                List<SysUserRole> sysUserRoleList = new ArrayList<>(roleIds.length) ;
                for (String roleId : roleIds) {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setRoleId(Long.valueOf(roleId));
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRoleList.add(sysUserRole) ;
                }
                sysUserRoleService.saveBatch(sysUserRoleList) ;//插入（批量）
            }
        }
        return save;
    }
}
